﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Coffee_Restaurant.DAL;
using Coffee_Restaurant.Database;
using Coffee_Restaurant.UserControls;
using MetroFramework;

namespace Coffee_Restaurant.Forms.AreaTable
{
    public partial class ManagerAreaTable : Form
    {
        private int RowIndex { get; set; }
        private int ColumnIndex { get; set; }

        private int AreaId { get; set; }
        private string NumberTable { get; set; }

        private Button _buttonTableNumber;
        public ManagerAreaTable()
        {
            InitializeComponent();

        }



        private void btn_Click(object sender, EventArgs e)
        {
            var button = sender as Button;
            if (button != null)
                switch (button.Name)
                {
                    case "btnAddArea":
                        var areaAdd = new AreaAddEdit { lblTitle = { Text = "Thêm khu vực bàn" } };
                        areaAdd.BtnAddArea += areaAdd_BtnAddArea;
                        areaAdd.ShowDialog();
                        break;
                    case "btnEditArea":
                        if (AreaId > 0)
                        {

                            using (var db = new DatabaseEntities())
                            {
                                var model = db.Areas.Find(AreaId);
                                var areaEdit = new AreaAddEdit
                                {
                                    lblTitle = { Text = "Sửa khu vực bàn" },
                                    AreaId = AreaId,
                                    btnSave = { Name = "btnSaveEdit" },
                                    txtNameArea = { Text = model.Name },
                                    txtDescription = { Text = model.Description }
                                };
                                areaEdit.BtnEditArea += areaEdit_BtnEditArea;
                                areaEdit.ShowDialog();
                            }
                        }
                        else
                        {
                            CustomMessageBox.Show("Bạn chưa chọn khu vực cần sửa", "", "alert", MetroColorStyle.Default);
                        }

                        break;
                    case "btnDeleteArea":
                        if (AreaId > 0)
                        {
                            DialogResult dialogResult = CustomMessageBox.Show("Bạn chắc chắn muốn xóa bàn này", "", "confirm", MetroColorStyle.Default);
                            if (dialogResult == DialogResult.Yes)
                            {
                                var areaDa = new AreaDa();
                                if (areaDa.DeleteArea(AreaId) > 0)
                                {
                                    //remove node tree
                                    treeViewArea.Nodes[AreaId.ToString()].Remove();
                                }
                            }
                        }
                        else
                        {
                            CustomMessageBox.Show("Bạn chưa chọn khu vực cần xóa", "", "alert", MetroColorStyle.Default);
                        }
                        break;
                    case "btnAddTable":
                        var tableAdd = new TableAddEdit { lblTitle = { Text = "Thêm số bàn" } };
                        tableAdd.AreaId = AreaId; //set areaid de cho combobox su dung default
                        tableAdd.BtnAddTable += tableAdd_BtnAddTable;
                        tableAdd.ShowDialog();
                        break;
                    case "btnEditTable":
                        if (!string.IsNullOrEmpty(NumberTable))
                        {
                            using (var db = new DatabaseEntities())
                            {
                                //tim kiem theo ten ban
                                var model = db.Tables.FirstOrDefault(t => t.Name == NumberTable);
                                if (model != null)
                                {
                                    var tableEdit = new TableAddEdit()
                                    {
                                        lblTitle = { Text = "Sửa số bàn" },
                                        numberTable = NumberTable,
                                        AreaId = model.AreaId,
                                        btnSave = { Name = "btnSaveEdit" },
                                        txtName = { Text = model.Name },
                                        txtDescription = { Text = model.Description }
                                    };

                                    tableEdit.BtnEditTable += tableEdit_BtnEditTable;
                                    tableEdit.ShowDialog();
                                }
                            }
                        }
                        else
                        {
                            CustomMessageBox.Show("Bạn chưa chọn bàn cần sửa", "", "alert", MetroColorStyle.Default);
                        }
                        break;
                    case "btntableNumber":
                        NumberTable = button.Text;
                        break;
                    case "btnDeleteTable":

                        if (!string.IsNullOrEmpty(NumberTable))
                        {
                            DialogResult dialogResult = CustomMessageBox.Show("Bạn chắc chắn muốn xóa bàn này", "", "confirm", MetroColorStyle.Default);
                            if (dialogResult == DialogResult.Yes)
                            {
                                var tableDa = new TableDa();
                                if (tableDa.DeleteTable(NumberTable) > 0)
                                {
                                    //remove
                                    foreach (var control in flowLayoutPanelTable.Controls.Find("btntableNumber", true))
                                    {
                                        if (control.Text == NumberTable)
                                        {
                                            flowLayoutPanelTable.Controls.Remove(control);
                                            //load tree
                                            //get current node select
                                            //TreeNode currentNode = treeViewArea.SelectedNode;
                                            ReloadArea();
                                            //treeViewArea.SelectedNode = currentNode;
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            CustomMessageBox.Show("Bạn chưa chọn bàn cần xóa", "", "alert", MetroColorStyle.Default);
                        }
                        break;
                }
        }

        void tableEdit_BtnEditTable(string oldname, string areaId, string name)
        {
            TreeNode[] node = treeViewArea.Nodes.Find(areaId, true);
            //load treeview
            treeViewArea.SelectedNode = node[0];
            foreach (var control in flowLayoutPanelTable.Controls.Find("btntableNumber", true))
            {
                if (control.Text == oldname)
                {
                    control.Text = name;
                }
            }

        }

        void tableAdd_BtnAddTable(string name)
        {
            try
            {
                if (name != null)
                {

                    AddTableNumber(name);
                    //load treeview
                    ReloadArea();
                }
            }
            catch (Exception)
            {

            }
        }


        void AddTableNumber(string name)
        {
            _buttonTableNumber = new Button();
            _buttonTableNumber.BackgroundImage = global::Coffee_Restaurant.Properties.Resources.table;
            _buttonTableNumber.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            _buttonTableNumber.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            _buttonTableNumber.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            _buttonTableNumber.FlatAppearance.BorderSize = 0;
            _buttonTableNumber.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            _buttonTableNumber.Font = new System.Drawing.Font("Camlam", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            _buttonTableNumber.ForeColor = System.Drawing.Color.White;
            _buttonTableNumber.Location = new System.Drawing.Point(184, 248);
            _buttonTableNumber.Name = "btntableNumber";
            _buttonTableNumber.Size = new System.Drawing.Size(80, 80);
            _buttonTableNumber.Margin = new Padding(10);
            _buttonTableNumber.TabIndex = 0;
            _buttonTableNumber.Text = name;
            _buttonTableNumber.UseVisualStyleBackColor = true;
            _buttonTableNumber.Cursor = System.Windows.Forms.Cursors.Hand;
            _buttonTableNumber.Click += btn_Click;
            _buttonTableNumber.MouseHover += btn_MouseHover;
            _buttonTableNumber.MouseLeave += btn_MouseLeave;

            flowLayoutPanelTable.Controls.Add(_buttonTableNumber);

        }


        private void btn_MouseHover(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                btn.BackgroundImage = global::Coffee_Restaurant.Properties.Resources.table_hover;
            }
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                btn.BackgroundImage = global::Coffee_Restaurant.Properties.Resources.table;
            }
        }



        //edit node tree
        void areaEdit_BtnEditArea(string key, string name)
        {
            try
            {
                if (name != null && key != null)
                {
                    treeViewArea.Nodes[key].Text = name;
                }
            }
            catch (Exception)
            {

            }
        }

        //add new node tree
        public void areaAdd_BtnAddArea(string key, string name)
        {
            try
            {
                if (name != null && key != null)
                {
                    treeViewArea.Nodes.Add(key, name + " (0)");
                    TreeNode[] node = treeViewArea.Nodes.Find(key, true);
                    //load treeview
                    treeViewArea.SelectedNode = node[0];
                    var font = new Font(treeViewArea.Font, FontStyle.Underline);
                    treeViewArea.SelectedNode.NodeFont = font;
                }
            }
            catch (Exception)
            {

            }
        }

        private void ManagerAreaTable_Load(object sender, EventArgs e)
        {
            ReloadArea();
        }

        public void ReloadArea()
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.sp_AreasDataSoure().ToList();
                var sumCount = db.sp_AreasDataSoure().Sum(x => x.CountTable);
                treeViewArea.Nodes.Clear();
                treeViewArea.Nodes.Add("0", "Tất cả (" + sumCount + ")");
                foreach (var spAreasDataSoureResult in model)
                {
                    treeViewArea.Nodes.Add(spAreasDataSoureResult.AreaId.ToString(), spAreasDataSoureResult.Name + " (" + spAreasDataSoureResult.CountTable + ")");
                }
            }
        }
        public void ReloadTable()
        {
            using (var db = new DatabaseEntities())
            {
                var modelTable = db.Tables.ToList();
                flowLayoutPanelTable.Controls.Clear();
                foreach (var table in modelTable)
                {
                    AddTableNumber(table.Name);
                }
            }
        }

        private void treeViewArea_AfterSelect(object sender, TreeViewEventArgs e)
        {
            AreaId = Convert.ToInt32(treeViewArea.Nodes[e.Node.Index].Name);
            //load table thuoc area nay
            using (var db = new DatabaseEntities())
            {
                var model = db.Tables.Where(t => t.AreaId == AreaId).ToList();
                if (AreaId == 0)
                {
                    model = db.Tables.ToList();
                }
                flowLayoutPanelTable.Controls.Clear();
                foreach (var table in model)
                {
                    AddTableNumber(table.Name);
                }
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void contextMenuStripTable_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "reloadTable":
                    ReloadTable();
                    break;
            }
        }

        private void contextMenuStripArea_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "toolStripMenuReloadArea":
                    ReloadArea();
                    break;
            }
        }




        //esc to exit
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                ReloadTable();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}
